package edu.nf.supermarket.web.controller.admin;

import edu.nf.supermarket.base.BaseController;
import edu.nf.supermarket.config.FilePathConfig;
import edu.nf.supermarket.entity.Classify;
import edu.nf.supermarket.entity.Commodity;
import edu.nf.supermarket.entity.CommodityImage;
import edu.nf.supermarket.result.ResultVO;
import edu.nf.supermarket.service.ClassifyService;
import edu.nf.supermarket.service.CommodityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;

/**
 * @author yjj
 * @date 2025-06-17
 */
@RestController
@RequestMapping("/productManage")
public class ProductManagementController extends BaseController {
    @Autowired
    private CommodityService service;
    @Autowired
    private FilePathConfig filePathConfig;
    @Autowired
    private ClassifyService classifyService;

    /**
     * 获取所有商品信息
     *
     * @return
     */
    @GetMapping("/getAllCommodity")
    public ResultVO<List<Commodity>> getAllCommodity() {
        return success(service.findAllCommodity());
    }

    /**
     * 添加商品
     *
     * @param commodity
     * @return
     */
    @PostMapping("/addCommodity")
    public ResultVO<Integer> addCommodity(@RequestBody Commodity commodity) {
        System.out.println("commodity = " + commodity);
        service.addCommodity(commodity);
        return success(commodity.getCommodityId());
    }

    /**
     * 添加商品图片
     *
     * @param commodityId
     * @param commodityPic
     * @return
     * @throws IOException
     */
    @PostMapping("/addCommodityPic")
    public ResultVO<String> addCommodityPic(@RequestParam("commodityId") Integer commodityId,
                                            @RequestParam("commodityPic") MultipartFile commodityPic) throws IOException {
        if (!isValidFileType(commodityPic.getContentType())) {
            return fail(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(), "文件格式错误");
        }


        // 使用配置的路径
        String uploadDir = filePathConfig.getProductPath();

        // 处理跨平台路径
        Path uploadPath = Paths.get(uploadDir).normalize();
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 生成唯一文件名
        String fileName = UUID.randomUUID() + "." + getFileExtension(commodityPic.getOriginalFilename());
        Path filePath = uploadPath.resolve(fileName);

        try {
            commodityPic.transferTo(filePath.toFile());

            // 存储相对路径（关键！）
            String relativePath = "/static/photo/products/" + fileName;
            service.addCommodityPic(commodityId, relativePath);

            return success(relativePath);
        } catch (IOException e) {
            e.printStackTrace();
            return fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), "头像上传失败");
        }
    }

    // 获取文件扩展名
    private String getFileExtension(String filename) {
        return filename.substring(filename.lastIndexOf(".") + 1);
    }

    /**
     * 校验文件类型
     *
     * @return
     */
    public boolean isValidFileType(String fileType) {
        String[] validFileTypes = {"image/jpeg", "image/png", "image/jpg", "image/webp"};
        for (String type : validFileTypes) {
            if (type.equals(fileType)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取商品分类数据
     *
     * @return
     */
    @GetMapping("/getAllClassify")
    public ResultVO<List<Classify>> getAllClassify() {
        List<Classify> allClassify = classifyService.findAllClassify();
        return success(allClassify);
    }

    /**
     * 修改商品信息
     */
    @PostMapping("/updateCommodity")
    public ResultVO<String> updateCommodity(@RequestBody Commodity commodity) {
        service.updateCommodity(commodity);
        return success("修改成功");
    }

    /**
     * 修改商品图片
     */
    @PostMapping("/updateCommodityPic")
    public ResultVO<String> updateCommodityPic(@RequestParam("commodityId") Integer commodityId,
                                               @RequestParam("commodityPic") MultipartFile commodityPic) throws IOException {
        if (!isValidFileType(commodityPic.getContentType())) {
            return fail(HttpStatus.UNSUPPORTED_MEDIA_TYPE.value(), "文件格式错误");
        }


        // 使用配置的路径
        String uploadDir = filePathConfig.getProductPath();

        // 处理跨平台路径
        Path uploadPath = Paths.get(uploadDir).normalize();
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 生成唯一文件名
        String fileName = UUID.randomUUID() + "." + getFileExtension(commodityPic.getOriginalFilename());
        Path filePath = uploadPath.resolve(fileName);

        try {
            commodityPic.transferTo(filePath.toFile());

            // 存储相对路径（关键！）
            String relativePath = "/static/photo/products/" + fileName;
            service.updateCommodityPic(new CommodityImage(null, commodityId, relativePath));

            return success(relativePath);
        } catch (IOException e) {
            e.printStackTrace();
            return fail(HttpStatus.INTERNAL_SERVER_ERROR.value(), "头像上传失败");
        }
    }
    /**
     * 修改商品状态
     */
    @PostMapping("/updateCommodityStatus")
    public ResultVO<Commodity> updateCommodityStatus(@RequestParam("commodityId") Integer commodityId,
                                                     @RequestParam("commodityStatus")Byte commodityStatus){
        service.updateCommodityStatus(commodityId,commodityStatus);
        return success();
    }
}
